package com.zhentao.controller;

import com.zhentao.mapper.DishInfoMapper;
import com.zhentao.mapper.DishSpecMapper;
import com.zhentao.mapper.DishTasteMapper;
import com.zhentao.pojo.Order;
import com.zhentao.service.OrderService;
import com.zhentao.service.OrderItemService;
import com.zhentao.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import com.zhentao.vo.OrderItemVO;
import com.zhentao.vo.DateRangeRequest;
import com.zhentao.vo.CreateOrderRequest;
import com.zhentao.vo.UpdateOrderRequest;
import java.util.Calendar;

@RestController
@RequestMapping("orders")
@CrossOrigin
public class OrderController {
    @Autowired
    OrderService orderService;
    
    @Autowired
    OrderItemService orderItemService;

    @Autowired
    DishInfoMapper dishInfoMapper;

    @Autowired
    DishSpecMapper dishSpecMapper;

    @Autowired
    DishTasteMapper dishTasteMapper;



    
    // 判断是否是今天的订单
    private boolean isToday(Date orderDate, Date today) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(orderDate).equals(sdf.format(today));
    }
    
    //今日订单
    @RequestMapping("findalltoday")
    public Result findall() {
        try {
            List<Order> orderList = orderService.list();
            //判断是否是今日的订单
            Date today = new Date();

            // 过滤出今日的订单
            List<Order> todayOrders = orderList.stream()
                    .filter(order -> isToday(order.getCreateTime(), today))
                    .collect(Collectors.toList());
            
            return Result.success(todayOrders);
        } catch (Exception e) {
            return Result.error("获取今日订单失败: " + e.getMessage());
        }
    }

    //历史订单
    @RequestMapping("findalllishi")
    public Result findalllishi() {
        try {
            List<Order> orderList = orderService.list();

            Date today = new Date();

            // 过滤出历史订单（非今日的订单）
            List<Order> historyOrders = orderList.stream()
                    .filter(order -> !isToday(order.getCreateTime(), today))
                    .collect(Collectors.toList());
            
            return Result.success(historyOrders);
        } catch (Exception e) {
            return Result.error("获取历史订单失败: " + e.getMessage());
        }
    }
    
    // 按日期范围查询历史订单
    @PostMapping("findalllishiByDateRange")
    public Result findalllishiByDateRange(@RequestBody DateRangeRequest request) {
        try {
            List<Order> orderList = orderService.list();
            
            // 解析日期范围
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date startDate = sdf.parse(request.getStartDate());
            Date endDate = sdf.parse(request.getEndDate());
            
            // 设置结束日期为当天的23:59:59
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endDate);
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);

            
            // 过滤出指定日期范围内的订单
            List<Order> historyOrders = orderList.stream()
                    .filter(order -> {
                        Date orderDate = order.getCreateTime();
                        return orderDate.after(startDate) && orderDate.before(endDate);
                    })
                    .collect(Collectors.toList());
            
            return Result.success(historyOrders);
        } catch (Exception e) {
            return Result.error("按日期范围查询历史订单失败: " + e.getMessage());
        }
    }
    
    // 获取订单明细
    @GetMapping("{orderId}/items")
    public Result getOrderItems(@PathVariable Integer orderId) {
        try {
            List<OrderItemVO> items = orderItemService.getOrderItemVOsByOrderId(orderId);
            return Result.success(items);
        } catch (Exception e) {
            return Result.error("获取订单明细失败: " + e.getMessage());
        }
    }
    
    // 删除订单
    @DeleteMapping("{orderId}")
    public Result deleteOrder(@PathVariable Integer orderId) {
        try {
            // 先删除订单明细
            orderItemService.removeByOrderId(orderId);
            // 再删除订单
            boolean result = orderService.removeById(orderId);
            if (result) {
                return Result.success("订单删除成功");
            } else {
                return Result.error("订单删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除订单失败: " + e.getMessage());
        }
    }
    
    // 反位订单
    @PostMapping("{orderId}/reverse")
    public Result reverseOrder(@PathVariable Integer orderId) {
        try {
            Order order = orderService.getById(orderId);
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            // 更新订单状态为待付款
            order.setStatus("pending");
            order.setPayTime(null);
            order.setCompleteTime(null);
            
            boolean result = orderService.updateById(order);
            if (result) {
                return Result.success("订单反位成功");
            } else {
                return Result.error("订单反位失败");
            }
        } catch (Exception e) {
            return Result.error("反位订单失败: " + e.getMessage());
        }
    }
    
    // 结账
    @PostMapping("{orderId}/checkout")
    public Result checkoutOrder(@PathVariable Integer orderId) {
        try {
            Order order = orderService.getById(orderId);
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            // 更新订单状态为已完成
            order.setStatus("completed");
            order.setCompleteTime(new Date());
            
            boolean result = orderService.updateById(order);
            if (result) {
                return Result.success("结账成功");
            } else {
                return Result.error("结账失败");
            }
        } catch (Exception e) {
            return Result.error("结账失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建订单
     * @param request 创建订单请求
     * @return 创建结果
     */
    @PostMapping("/create")
    public Result createOrder(@RequestBody CreateOrderRequest request) {
        try {
            return orderService.createOrder(request);
        } catch (Exception e) {
            return Result.error("创建订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新订单
     * @param request 更新订单请求
     * @return 更新结果
     */
    @PutMapping("/update")
    public Result updateOrder(@RequestBody UpdateOrderRequest request) {
        try {
            return orderService.updateOrder(request);
        } catch (Exception e) {
            return Result.error("更新订单失败: " + e.getMessage());
        }
    }
}

